package com.pinoc.common;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Date: 2019-09-13 9:55
 * Author: pinoc
 * Desc:
 */
public class IoUtil {

	public static List<String> readFile(String filePath) {
		File file = new File(filePath);
		BufferedReader in = null;
		List<String> list = new ArrayList<String>();
		try {
			in = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
			String read = "";
			while ((read = in.readLine()) != null) {
				list.add(read);
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return list.isEmpty() ? null : list;
	}

	public static void writeTxt(String filePath, List<String> listInfo) {
		File file = new File(filePath);
		OutputStream os = null;
		try {
			os = new FileOutputStream(file, true);
			for (String s : listInfo) {
				byte[] data = s.getBytes();
				os.write(data, 0, data.length); // 3、写入文件
				os.write("\r\n".getBytes());
			}
			os.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static String decToHex(int dec) {
		String hex = Integer.toHexString(dec);
		switch (hex.length()) {
			case 1:
				hex = "000" + hex;
				break;
			case 2:
				hex = "00" + hex;
				break;
			case 3:
				hex = "0" + hex;
				break;
			default:
				break;
		}
		return hex;
	}

	public static void writeTxt(String path,String line) {
		FileWriter fw = null;
		try {
			File f=new File(path);
			fw = new FileWriter(f, true);
		} catch (IOException e) {
			e.printStackTrace();
		}
		PrintWriter pw = new PrintWriter(fw);
		pw.println(line);
		pw.flush();
		try {
			fw.flush();
			pw.close();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
